package com.aw.manual.ejemplo013;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * User: gmc
 * Date: 03/06/2010
 */
@Component
public class BeanNameSetterPostProcessor implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Field field = getFieldForBeanName(bean);
        if (field != null) {
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field,bean,beanName);
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    private Field getFieldForBeanName(Object bean) {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            BeanName beanNameAnnot = field.getAnnotation(BeanName.class);
            if (beanNameAnnot != null) {
                return field;
            }
        }
        return null;
    }

}
